
import { v4 } from 'uuid'
import { useState } from 'react'
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'

import { Http } from '../Utils/Api'
import { FieldConfig } from '../Config'
import { replaceDataByKey } from '../Utils'
import { GetMenuFieldMapping } from '../Config/theme'
import { menuStore, fromStore } from '../Config/zustand'
import { DevextremeDataGrid } from '../Utils/Devextreme'


const tableConfig = {
    allowColumnReordering: true, // 允许重新排序
    showColumnHeaders: true, // 是否显示列标题
    columnMinWidth: 50, // 列最小宽度
    columnAutoWidth: true, // 自动宽度
    allowColumnResizing: true, //是否可调整列宽
    columnResizingMode: 'widget', //列宽状态  nextColumn 总组件宽度不会更改  widget 所有其他列保持其宽度
    repaintChangesOnly: true, // 动态摘要 ,
    focusedRowEnabled: true, // 是否聚焦
    showBorders: false, // 是否外边框
    showRowLines: false, // 子单元格底边框
    showColumnLines: false, // 子单元格竖向边框
    rowAlternationEnabled: true, //斑马格
    columnFixing: true, // 启用 固定列
    searchPanel: true, // 启用头部筛选
    headerFilter: false, // 启用 筛选器
    sorting: 'multiple', //排序功能 不可 none 单选 single 多选 multiple
    columnDlyState: true, // 是否启用自定义列
    columnDlyWidth: 120, // 自定义列宽度
    filterRow: false, // 启用 行筛选
    filterRowApplyFilter: 'none', // 行筛选方式  none 自动搜索 onClick 点击头部搜索
    rowDragging: false, // 启用行拖拽
    rowDraggingShowDragIcons: true, //是否有把手
    export: false, // 启用 导出
    exportAllowExportSelectedData: true, // 全部导出
    selectionMode: 'none', //选中数据行 不可 none 单选 single 多选 multiple
    selectionAllowSelectAll: true, // 是否全选
    selectionSelectAllMode: 'allPages', // 全选方式 'allPages' 所有记录, 'page' 当前页面记录
    selectionShowCheckBoxesMode: 'onLongTap', // 选择方式 none 不可选中 always 选择框选中 onClick 点击选中  onLongTap 长按选中
    columnChooser: true, //启用 列选择器
    columnChooserMode: 'select', // 列选择器模式 dragAndDrop拖拽   select选择
    columnChooserSearch: true, // 启用 列选择器搜索框
    columnChooserSearchPlaceholder: '默认文字', // 搜索框默认文字
    columnChooserSelectionAll: true, // 列选择器 全选按钮
    columnChooserSelectionClick: true, // 列选择器 单击选择
    columnChooserSelectionRecursive: true, // 列选择器 递归选择 (呈现树形)
    groupPanel: false, // 启用 分组
    groupPanelAutoExpandAll: true, // 分组自动展开
    groupPanelAllowColumnDragging: true, // 是否可以取消分组
    groupingExpandMode: 'buttonClick', // 分组 展开模式 rowClick 点击行 buttonClick 点击按钮
    groupingContextMenuEnabled: true, // 分组 启用右键菜单
    groupingAutoExpandAll: true, // 分组 自动展开
    groupingAllowCollapsing: true, // 是否允许折叠 (false 只能通过编程控制)
}

const MenuConfigField = ({ url }) => {
    const { fieldConfig, updateFieldConfig } = menuStore()
    const [dataSource, setDataSource] = useState()
    const { updateFromData, updateFromLoad } = fromStore()

    const { send } = useRequest(params => Http({ url: 'getMenuColumnList', params }), { immediate: false })

    useMount(async () => {
        const { data } = await send({ MenuType: GetMenuFieldMapping[url] })

        if (!fieldConfig || fieldConfig.length === 0) {

            const FieldData = data.map(key => {
                return ({
                    uuid: v4(),
                    dataField: key, caption: '映射名称', valueType: 'Input', rules: false, sortId: 99,
                    isMapping: false, mappingType: '', mappingData: '', mappingValue: '', mappingLable: '',
                    visible: true, isAdded: true, isModify: true, isSearch: true,
                    fixed: false, fixedPosition: 'left', dataType: '', format: '',
                    minWidth: 50, width: 160, alignment: 'center', cssClass: '', allowResizing: true,
                    allowGrouping: true, autoExpandGroup: true, groupIndex: 0,
                    allowReordering: false, allowSorting: true, defaultSortIndex: 0, defaultSortOrder: 'asc',
                    allowHeaderFiltering: true, allowFiltering: true, showInColumnChooser: true,
                    calculateCellValue: '', customizeText: '',
                })
            })
            setDataSource(FieldData)
            updateFieldConfig(FieldData)
        } else {
            const newData = data.map(key => {
                const obj = fieldConfig.find(v => v.dataField === key)
                if (obj) {
                    return obj
                } else {
                    return ({
                        uuid: v4(),
                        dataField: key, caption: '映射名称', valueType: 'Input', rules: false, sortId: 9999,
                        isMapping: false, mappingType: '', mappingData: '', mappingValue: '', mappingLable: '',
                        visible: true, isAdded: true, isModify: true, isSearch: true,
                        fixed: false, fixedPosition: 'left', dataType: '', format: '',
                        minWidth: 50, width: 160, alignment: 'center', cssClass: '', allowResizing: true,
                        allowGrouping: true, autoExpandGroup: true, groupIndex: 0,
                        allowReordering: false, allowSorting: true, defaultSortIndex: 0, defaultSortOrder: 'asc',
                        allowHeaderFiltering: true, allowFiltering: true, showInColumnChooser: true,
                        calculateCellValue: '', customizeText: '',
                    })
                }
            })
            const sortIdData = newData.sort((a, b) => a.sortId - b.sortId)
            setDataSource(sortIdData)
        }
    })

    const DevEvent = useEventEmitter()
    DevEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'fieldBack') {
            const newData = replaceDataByKey(dataSource, { uuid: v4(), ...data }, data.dataField, 'dataField')
            const sortIdData = newData.sort((a, b) => a.sortId - b.sortId)
            updateFieldConfig(sortIdData)
            setDataSource([...sortIdData])
            updateFromData({})
            updateFromLoad(false)
        }
    })
    const ColumnOptions = ({ data, fields }) => [{ title: '修改', smallTitle: '修改菜单', modalType: 'model', page: 'FromFields', data: { fields, init: data, DevEvent } }]

    return (
        <div className='MenuConfigField'>

            {dataSource &&
                <DevextremeDataGrid
                    DataConfig={tableConfig}
                    dataSource={dataSource}
                    DevEvent={DevEvent}
                    fields={FieldConfig}
                    ColumnOptions={ColumnOptions}
                />
            }
        </div>
    );
};

export default MenuConfigField;